package com.braska.grave.netty.bean.aware;

import com.braska.grave.netty.annotation.Service;
import com.braska.grave.netty.worker.ServerWorker;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

/**
 * @author shenyuhang
 * @date 2020/3/31
 **/
public class NettyServerApplicationContextAware implements ApplicationContextAware, InitializingBean {
    private static final Logger logger = Logger.getLogger(NettyServerApplicationContextAware.class.getName());
    private Map<String, Object> serviceMap = new HashMap<>();
    ServerWorker runner;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        String address = applicationContext.getEnvironment().getProperty("remoteAddress");

        Map<String, Object> beans = applicationContext.getBeansWithAnnotation(Service.class);
        for (Object serviceBean : beans.values()) {

            Class<?> clazz = serviceBean.getClass();

            Class<?>[] interfaces = clazz.getInterfaces();

            for (Class<?> inter : interfaces) {
                String interfaceName = inter.getName();
                serviceMap.put(interfaceName, serviceBean);
            }
        }
        logger.info("已加载全部服务接口");
        runner = new ServerWorker(address, serviceMap);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        runner.open();
    }
}
